﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Web;

namespace Knowledgecast.Twitter.WPF.App
{
    /// <summary>
    /// Interaction logic for StatusUpdate.xaml
    /// </summary>
    public partial class StatusUpdate : UserControl
    {
        HttpWebRequest request;

        public StatusUpdate()
        {
            InitializeComponent();
        }

        public TwitterApi Twitter { get; set; }
        public Status ReplyToStatus { get; set; }

        private void Tweet(string message)
        {
            Tweet(message, null);
        }

        private void Tweet(string message, Status replyTo)
        {
            if (request == null)
            {
                try
                {
                    Twitter.UpdateStatus(txtTweet.Text, ReplyToStatus);
                    txtTweet.Text = string.Empty;
                }
                catch (Exception ex)
                {
                    txtError.Text = "Send failed";
                    Debug("Tweet crashed: " + ex.Message + ": " + ex.StackTrace);
                }
                finally
                {
                    request = null;
                }
            }
        }

        private void btnSend_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(txtTweet.Text) == false)
            {
                Tweet(txtTweet.Text);
            }
        }

        private void txtTweet_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter && String.IsNullOrEmpty(txtTweet.Text) == false)
            {
                Tweet(txtTweet.Text);
            }
        }

        public void Setup(string text, Status replyTo)
        {
            txtTweet.Text = text;
            ReplyToStatus = replyTo;
        }

        public void SetFocus()
        {
            txtTweet.Focus();
        }

        void Debug(string message)
        {
            string debugMessage = "[" + DateTime.Now.ToShortDateString() + DateTime.Now.ToShortTimeString() + "] - StatusUpdate";
            debugMessage += ": " + message;
            Trace.WriteLine(debugMessage);
        }
    }
}
